package com.wanlian.service.impl;

import com.wanlian.common.ConstantCode;
import com.wanlian.common.PageCondition;
import com.wanlian.common.RankType;
import com.wanlian.common.Verification;
import com.wanlian.dao.*;
import com.wanlian.entity.*;
import com.wanlian.error.ErrorCode;
import com.wanlian.error.SuccessCode;
import com.wanlian.model.ResultModel;
import com.wanlian.service.UserServices;
import com.wanlian.util.DESUtils;
import com.wanlian.util.DateUtil;
import com.wanlian.util.StringUtil;
import com.wanlian.util.Utils;
import com.wanlian.vo.Page;
import com.wanlian.vo.PasswordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServicesImpl implements UserServices {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserScoreDao userScoreDao;

    @Autowired
    private DeviceDao deviceDao;

    @Autowired
    private HistoryLoginDao historyLoginDao;

    @Autowired
    private UserPhoneCodeDao userPhoneCodeDao;

    @Autowired
    private ScoreHistoryDao scoreHistoryDao;

    @Autowired
    private TaskDao taskDao;

    @Autowired
    private InviteDao inviteDao;

    @Override
    public ResultModel doAdd(User user) {
        ResultModel resultModel = new ResultModel();
        List<User> users = userDao.queryUsersByPhone(user.getPhone());
        if (users.size() == 0) {
            user.setUserTag(Utils.getUUID());
            userDao.add(user);
            resultModel.setBresult(true);
        } else {
            resultModel.setBresult(false);
            resultModel.setMessage("该手机号已注册");
        }
        return resultModel;
    }

    @Override
    public ResultModel doAppEdit(User user) {
        User dbUser = this.userDao.queryById(user.getId());
        if (dbUser == null) {
            return new ResultModel(false, null, ErrorCode.NO_USER_ID);
        }
        if (StringUtil.hasValue(user.getHeadImg())) {
            dbUser.setHeadImg(user.getHeadImg());
        }
        if (StringUtil.hasValue(user.getEmail())) {
            dbUser.setEmail(user.getEmail());
        }
        if (StringUtil.hasValue(user.getUsername())) {
            dbUser.setUsername(user.getUsername());
        }
        if (dbUser.isSex() != user.isSex()) {
            dbUser.setSex(user.isSex());
        }
        if (user.getBirthday() != null) {
            dbUser.setBirthday(user.getBirthday());
        }
        userDao.update(dbUser);
        ResultModel resultModel = new ResultModel();
        resultModel.setBresult(true);
        resultModel.setMessage(SuccessCode.SUCCESS_UPD);
        resultModel.setObject(dbUser);
        return resultModel;
    }

    @Override
    public ResultModel doedit(User user) {
        userDao.update(user);
        ResultModel resultModel = new ResultModel();
        resultModel.setBresult(true);
        return resultModel;
    }

    /**
     * 删除用户
     *
     * @param user
     * @return
     */
    @Override
    public ResultModel doDeleteUser(User user) {
        User dbUser = userDao.queryById(user.getId());
        if (dbUser != null) {
            if (!dbUser.isEnable()) {
                return new ResultModel(false, "该用户已禁用");
            } else {
                dbUser.setEnable(false);
                userDao.update(dbUser);
                return new ResultModel(true);
            }
        } else {
            return new ResultModel(false, "用户id不存在");
        }
    }

    /**
     * 修改密码
     *
     * @param user
     * @return
     */
    @Override
    public ResultModel doModifyPassword(User user) {
        User dbUser = userDao.queryById(user.getId());
        if (dbUser != null) {
            if (!dbUser.isEnable()) {
                return new ResultModel(false, "该用户已禁用");
            } else {
                dbUser.setUpassword(user.getUpassword());
                userDao.update(dbUser);
                return new ResultModel(true);
            }
        } else {
            return new ResultModel(false, "用户id不存在");
        }
    }

    /**
     * 启用用户
     *
     * @param user
     * @return
     */
    @Override
    public ResultModel doEnableUser(User user) {
        User dbUser = userDao.queryById(user.getId());
        if (dbUser != null) {
            if (dbUser.isEnable()) {
                return new ResultModel(false, "该用户已启用");
            } else {
                dbUser.setEnable(true);
                userDao.update(dbUser);
                return new ResultModel(true);
            }
        } else {
            return new ResultModel(false, ErrorCode.NO_USER_ID);
        }
    }

    @Override
    public ResultModel queryUsers(PageCondition pageCondition) {
        return userDao.queryUsers(pageCondition);
    }

    @Override
    public List<User> queryByName(Page page, String name) {
        return userDao.queryUsersByName(page, name);
    }

    @Override
    public User queryUserByloginInfo(String phone, String password) {
        return userDao.queryUserByloginInfo(phone, password);
    }

    /**
     * 获取用户总积分
     *
     * @param userId
     * @return
     */
    @Override
    public ResultModel queryUserTotalScore(int userId) {
        ResultModel resultModel = new ResultModel();
        UserScore userScore = userScoreDao.queryUserScoreByUserId(userId);
        resultModel.setObject(userScore);
        return resultModel;
    }

    /**
     * 获取用户昨日积分
     *
     * @param userId
     * @return
     */
    @Override
    public ResultModel queryUserYestoryDayScore(int userId) {
        return null;
    }

    /**
     * 修改用户昵称
     *
     * @param user
     * @return
     */
    @Override
    public ResultModel doModifyUserName(User user) {
        User dbUser = this.userDao.queryById(user.getId());
        if (dbUser != null) {
            if (dbUser.isEnable()) {
                dbUser.setUsername(user.getUsername());
                this.userDao.update(dbUser);
                return new ResultModel(true);
            } else {
                ResultModel resultModel = new ResultModel(false);
                resultModel.setMessage(ErrorCode.USER_DISABLE);
                return resultModel;
            }
        } else {
            ResultModel resultModel = new ResultModel(false);
            resultModel.setMessage(ErrorCode.NO_USER_ID);
            return resultModel;
        }
    }

    /**
     * 用于联动模糊查询
     *
     * @param phoneOrName
     * @param page
     * @return
     */
    @Override
    public ResultModel queryByPartName(String phoneOrName, Page page) {
        return this.userDao.queryByPartName(phoneOrName, page);
    }

    @Override
    public List<User> queryAllUsers() {
        List<User> users = userDao.queryAll();
        return users;
    }

    /**
     * @param phone
     * @return
     */
    @Override
    public User queryUserByPhone(String phone) {
        return this.userDao.queryUserByPhone(phone);
    }

    @Override
    public ResultModel doAddLogin(HistoryLogin historyLogin) {
        ResultModel resultModel = new ResultModel();
        historyLoginDao.doAddLogin(historyLogin);
        resultModel.setBresult(true);
        return resultModel;
    }

    /**
     * 根据用户id查询最近一次登录记录
     *
     * @param userId
     * @return
     */
    @Override
    public ResultModel queryLastLoginHistoryById(int userId) {
        HistoryLogin historyLogin = this.historyLoginDao.queryLastLoginHistoryById(userId);
        return new ResultModel(true, historyLogin);
    }


    @Override
    public ResultModel queryByEnable(Page page) {
        ResultModel resultModel = userDao.queryByEnable(page, true);
        return resultModel;
    }

    /**
     * 添加短信验证码记录
     *
     * @param userPhoneCode
     * @return
     */
    @Override
    public ResultModel doAddPhoneCode(UserPhoneCode userPhoneCode) {
        ResultModel resultModel = new ResultModel();
        userPhoneCodeDao.add(userPhoneCode);
        return resultModel;
    }

    /**
     * 查询短信验证码
     *
     * @param phone
     * @return
     */
    @Override
    public ResultModel queryPhoneCodeByPhone(String phone) {
        UserPhoneCode code = userPhoneCodeDao.queryByPhone(phone);
        if (code == null) {
                return new ResultModel(false, ErrorCode.CODE_DEFAULT);
        } else {
            return new ResultModel(true, code);
        }
    }

    @Override
    public void doUpdateLoginTime(User user) {
        userDao.doUpdateLoginTime(user);
    }

    @Override
    public User queryById(int userId) {
        return userDao.queryById(userId);
    }


    @Override
    public ResultModel doBindIntAccount(User user) {
        ResultModel resultModel = new ResultModel();
        String intAccount = user.getIntAccount();
       // User dbuser = userDao.queryintAccountByAccount(intAccount);
       /* if (dbuser != null) {
            resultModel.setMessage("该int账号已绑定");
            resultModel.setBresult(false);
            return resultModel;
        }*/
        if (Verification.isIntAccount(intAccount)) {
            resultModel.setBresult(false);
            resultModel.setMessage("钱包地址不合法！");
            return resultModel;
        }
        User binduser = userDao.queryById(user.getId());
        if (!binduser.isEnable()) {
            resultModel.setMessage("该用户已禁用无法绑定");
            resultModel.setBresult(false);
            return resultModel;
        }
        /*if (binduser.getIntAccount() != null) {
            resultModel.setMessage("已绑定过int账号");
            resultModel.setBresult(false);
            return resultModel;
        }*/
        binduser.setIntAccount(user.getIntAccount());
        resultModel.setMessage("绑定成功");
        resultModel.setBresult(true);

        //查询是否有邀请送任务
        Invite invite=inviteDao.queryUserByIUid(user.getId());
        if(invite!=null){
            if(invite.getCompleted()==false){
                if(!invite.getBindInt()){
                    invite.setBindInt(true);
                    inviteDao.update(invite);
                }
                //若 int device 都绑定，则开始发放奖励
                if(inviteDao.queryUserInvite(user.getId())!=null){
                    this.inviteSend(invite,user);
                }

            }
        }

        return resultModel;
    }


    public  void inviteSend(Invite invite, User user){
        Task task=taskDao.queryTaskByName("邀请奖励");
        if(task==null){
            return;
        }
        //添加到积分表，历史表
        //被邀请人
        UserScore userScore=userScoreDao.queryUserScoreByParams(user.getId(),task.getRankType());
        if(userScore==null){
            UserScore userScore1=new UserScore();
            userScore1.setScore(task.getRank());
            userScore1.setRankType(task.getRankType());
            userScore1.setUserId(user.getId());
            userScore1.setModifyTime(DateUtil.currentTimestamp());
            userScoreDao.add(userScore1);
        }else{
            userScore.setModifyTime(DateUtil.currentTimestamp());
            userScore.setScore(userScore.getScore()+task.getRank());
            userScoreDao.update(userScore);
        }
        ScoreHistory scoreHistory=new ScoreHistory();
        scoreHistory.setTaskId(task.getId());
        scoreHistory.setUserId(user.getId());
        scoreHistory.setTrantype(ConstantCode.TRANS_INVITE);
        scoreHistory.setAddTime(DateUtil.currentTimestamp());
        scoreHistory.setRankType(task.getRankType());
        scoreHistory.setScore(task.getRank());
        scoreHistoryDao.add(scoreHistory);

        //添加到积分表，历史表
        //邀请人
        UserScore invite_userScore=userScoreDao.queryUserScoreByParams(invite.getUserId(),RankType.RANK_INT);
        if(invite_userScore==null){
            UserScore userScore1=new UserScore();
            userScore1.setScore(task.getRank());
            userScore1.setRankType(task.getRankType());
            userScore1.setUserId(invite.getUserId());
            userScore1.setModifyTime(DateUtil.currentTimestamp());
            userScoreDao.add(userScore1);
        }else{
            invite_userScore.setModifyTime(DateUtil.currentTimestamp());
            invite_userScore.setScore(invite_userScore.getScore()+task.getRank());
            userScoreDao.update(invite_userScore);
        }
        ScoreHistory invite_scoreHistory=new ScoreHistory();
        invite_scoreHistory.setUserId(invite.getUserId());
        invite_scoreHistory.setTaskId(task.getId());
        invite_scoreHistory.setTrantype(ConstantCode.TRANS_INVITE);
        invite_scoreHistory.setAddTime(DateUtil.currentTimestamp());
        invite_scoreHistory.setRankType(task.getRankType());
        invite_scoreHistory.setScore(task.getRank());
        scoreHistoryDao.add(invite_scoreHistory);

        invite.setCompleted(true);
        inviteDao.update(invite);

    }

    @Override
    public ResultModel doUnitedIntAccount(User user) {
        ResultModel resultModel = new ResultModel();
        User dbuser = userDao.queryById(user.getId());
        if (dbuser.getIntAccount() == null) {
            resultModel.setMessage("暂无int账号，无法解绑");
            resultModel.setBresult(false);
            return resultModel;
        }
        dbuser.setIntAccount(null);
        userDao.update(dbuser);
        resultModel.setMessage("解绑成功");
        resultModel.setBresult(true);
        return resultModel;
    }

    @Override
    public ResultModel queryUdsCount() {
        ResultModel resultModel = new ResultModel();
        //今日新增用户个数
        long userCount = userDao.queryUserCountToday();
        //今日激活设备个数
        long deviceCount = deviceDao.queryDeviceCountToday();
        //昨日生成积分
        double scoreYes = scoreHistoryDao.querySumScoreYes();
        Map<String, String> map = new HashMap<String, String>();
        map.put("usercount", userCount + "");
        map.put("devicecount", deviceCount + "");
        map.put("scoreyes", scoreYes + "");
        resultModel.setBresult(true);
        resultModel.setObject(map);
        return resultModel;
    }


    @Override
    public User queryUserByTag(String userTag) {
        User user = userDao.queryUserByTag(userTag);
        return user;
    }

    @Override
    public ResultModel queryIntDetailList(PageCondition pageCondition) {
        return userDao.queryIntDetailList(pageCondition);
    }

    @Override
    public ResultModel doEditPass(PasswordVo passwordVo, int userId) {
        ResultModel resultModel = new ResultModel(true);
        User user=userDao.queryById(userId);
        if(!StringUtil.hasValue(passwordVo.getNewPass())||!StringUtil.hasValue(passwordVo.getOldPass())){
            resultModel.setBresult(false);
            resultModel.setMessage("请输入密码");
            return resultModel;
        }
        String oldpass=passwordVo.getOldPass();
        String newpass=passwordVo.getNewPass();
        try {
            oldpass=DESUtils.encryptDES(user.getUserTag(), oldpass);
            newpass=DESUtils.encryptDES(user.getUserTag(), newpass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(!oldpass.equals(user.getUpassword())){
            resultModel.setBresult(false);
            resultModel.setMessage("登陆密码不正确");
            return resultModel;
        }
        user.setUpassword(newpass);
        userDao.update(user);
        resultModel.setMessage("修改成功");
        return resultModel;
    }
}
